﻿using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using Lamex.Base;
using Lamex.Library;
using Lamex.Library.CommonClass;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Lamex.mNC.UI
{
    public partial class frmNC_PN_CT_Scan_for_Processing : frmBaseChild
    {
        [DllImport("user32.dll")]
        public static extern int MessageBoxTimeoutA(IntPtr hWnd, string msg, string Caps, int type, int Id, int time);//引用DLL

        Lamex.mNC.ucControls.ucShowPic ucShowPicList = null;
        int PL_Count = 0, PL_TempCount = 0, YL_TempCount = 0;    
        //int BATCH_QTY = 0, BATCH_COUNT = 0, WAIT_QTY = 0;
        private static string path_Panel = @"\\tx-fs10\TX-FS1\LAMEX\NC\Porgram\Panel\Aluminum\";
        DataTable dt_Parameter_Tools = new DataTable();
        DataTable dt_Parameter_Machine = new DataTable();
        public frmNC_PN_CT_Scan_for_Processing()
        {
            InitializeComponent();
        }

        private void frmNC_PN_CT_Scan_for_Processing_Load(object sender, EventArgs e)
        {
            try { base.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理
            ClearControl();
            txtMachineNo.Text = Lamex.Common.Loginer.CurrentUser.Account;
            txtUser.Text= Lamex.Common.Loginer.CurrentUser.AccountName;
            InitCom();//开启COM扫码
            dt_Parameter_Tools = Common.GetDataTable.Get_Parameter_Tools();
            dt_Parameter_Machine = Common.GetDataTable.Get_Parameter_Machine();
        }
        #region   手工输入跟进表
        private void frmNC_PN_CT_Scan_for_Processing_Resize(object sender, EventArgs e)
        {
            groupControl1.Width = panelControl2.Width;//基本信息
            groupControl2.Width = panelControl1.Width / 3;//订单信息
            groupControl3.Width = panelControl1.Width / 3;//当前加工

            groupControl5.Height = panelControl2.Height / 2;
            groupControl6.Height = panelControl2.Height / 2;
            groupControl7.Height = panelControl2.Height / 2;
            groupControl8.Height = panelControl2.Height / 2;
        }

        private void txtOrderNumber_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                try
                {
                    //ClearControl();
                    //手工输入跟进表号
                    string OrderNumber = txtOrderNumber.Text.Trim();
                    if (!string.IsNullOrEmpty(OrderNumber))
                    {
                        DataTable dt = Common.GetDataTable.Get_Part_Detailed(OrderNumber);
                        if (dt.Rows.Count > 0)
                        {
                            GetData_ComboxList(dt);//获取下拉列表                        
                        }
                    }
                }
                catch (Exception ex)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
                }
            }
        }
        public void GetData_ComboxList(DataTable dt)
        {
            cbDwgNo.Text = "";
            cbPartNo.Text = "";
            cbPartNo.Properties.Items.Clear();
            cbDwgNo.Properties.Items.Clear();
            foreach (DataRow row in dt.Rows)
            {
                cbPartNo.Properties.Items.Add(row["Part_No"]);
                cbDwgNo.Properties.Items.Add(row["Drawing_No"]);
            }
            if (cbPartNo.Properties.Items.Count <= 1)
                cbPartNo.SelectedIndex = 0;
            cbDwgNo.SelectedIndex = 0;
            ShowPic(cbDwgNo.Text, cbPartNo.Text);
        }
        public void ShowPic(string DWGNO, string PARTNO)
        {
            List<string> listPic = new List<string>();
            listPic = Common.GetShowPic.ShowPic_STD(DWGNO, PARTNO);
            ucShowPicList = new ucControls.ucShowPic();
            PicControl.Invoke(new Action(() => { PicControl.Controls.Clear(); }));
            if (listPic.Count > 0)
            {
                // ucShowPicList = new ucControls.ucShowPic();
                ucShowPicList.LoadImageList(listPic);
                ucShowPicList.Dock = DockStyle.Fill;
                // PicControl.Invoke(new Action(() => { PicControl.Controls.Add(ucShowPicList); }));
            }
            PicControl.Invoke(new Action(() => { PicControl.Controls.Add(ucShowPicList); }));
        }

        private void cbPartNo_TextChanged(object sender, EventArgs e)
        {
            ShowPic(cbDwgNo.Text, cbPartNo.Text);
        }

        private void cbDwgNo_TextChanged(object sender, EventArgs e)
        {
            ShowPic(cbDwgNo.Text, cbPartNo.Text);
        }
        public void ClearControl()
        {
            barCode_ZWS_L.Invoke(new Action(() => { barCode_ZWS_L.Visible = false; }));
            barCode_ZWS_R.Invoke(new Action(() => { barCode_ZWS_R.Visible = false; }));
            barCode_ZPL_L.Invoke(new Action(() => { barCode_ZPL_L.Visible = false; }));
            barCode_ZPL_R.Invoke(new Action(() => { barCode_ZPL_R.Visible = false; }));

            PicControl.Invoke(new Action(() => { PicControl.Controls.Clear(); }));
            txtOrderNumber.Invoke(new Action(() => { txtOrderNumber.Text = ""; }));
            // txtProcessQty.Invoke(new Action(() => { txtProcessQty.Text = ""; }));
            cbDwgNo.Invoke(new Action(() => { cbDwgNo.Text = ""; }));
            cbPartNo.Invoke(new Action(() => { cbPartNo.Text = ""; }));

            PL_TempCount = 0;
            PL_Count = 0;
            YL_TempCount = 0;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (txtOrderQty.Text.Length <= 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("加工数量不能为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtOrderQty.Focus();
                return;
            }
            int OrderQty = Convert.ToInt32(txtOrderQty.Text.Trim());
            string strOrderNo = txtOrderNumber.Text.Trim();
            string strDwgNo = cbDwgNo.Text.Trim();
            string strPartNo = cbPartNo.Text.Trim();
            //生成NC转码程序
            GetNCProject(strOrderNo, strPartNo, strDwgNo);
           
            //Calculate.Cal_BatchQtyHelper.Get_BatchQty(strOrderNo, strDwgNo, strPartNo, OrderQty, out BATCH_QTY, out WAIT_QTY, out BATCH_COUNT);
            ////显示二维码
            //PL_Count = BATCH_COUNT;
            //PL_TempCount = Common.GetSerialNumber.GetSerialNo(strOrderNo + "_" + strPartNo);
            //YL_TempCount = Common.GetSerialNumber.GetSerialNo_YL(strOrderNo + "_" + strPartNo);
            //ShowQRCode(OrderQty, BATCH_QTY, WAIT_QTY, strOrderNo + "_" + strPartNo, PL_TempCount);

            //计算待加工数量
            txtWaitProcessQty.Invoke(new Action(() =>
            {
                txtWaitProcessQty.Text = Common.SQLHelper.GetScanQty(txtOrderNumber.Text.Trim() + "_" + cbPartNo.Text.Trim(), Convert.ToInt32(txtOrderQty.Text.Trim())).ToString();
            }));
            //生成二维码
            ShowInfo(strOrderNo, strDwgNo, strPartNo, OrderQty);
            //得到每日产量
            GetOutPutInfo();
        }

        #endregion
        #region 公共方法
        public void GetNCProject(string OrderNumber,string PartNo,string DWGNO)
        {
            try
            {
                SplashScreenTool.ShowSplashScreen(typeof(WaitForm1));
                string path = @"\\Tx-fs10\tx-fs1\LAMEX\NC\Porgram\Panel\Aluminum\";
                List<string> DWG_No_Error = new List<string>();
                List<string> Part_No_Error = new List<string>();
                             
                double tolerance = txtTolerance.Text.Trim().Length > 0 ? Convert.ToDouble(txtTolerance.Text.Trim()) : 0;//公差
                decimal qty = Convert.ToDecimal(txtOrderQty.Text.ToString());
                bool IsCustom = true;
                bool IsTest = false;
                DataTable dt_Cache = Common.GetCacheTable.Get_Cache_Table(PartNo, DWGNO, OrderNumber, tolerance, dt_Parameter_Tools, dt_Parameter_Machine, qty, IsCustom, IsTest);//缓存表
                                                                                                                                                                                  //首先判断临时dt_Cache数据是否规范
                if (dt_Cache.Rows.Count > 0)
                {
                    bool flag_error = false;
                    for (int i = 0; i < dt_Cache.Rows.Count; i++)
                    {
                        double EXPOSED_LENTH = dt_Cache.Rows[i]["EXPOSED_LENTH"].ToString().Length > 0 ? Convert.ToDouble(dt_Cache.Rows[i]["EXPOSED_LENTH"].ToString()) : 0;
                        double PROCESS_DEPTH = dt_Cache.Rows[i]["PROCESS_DEPTH"].ToString().Length > 0 ? Convert.ToDouble(dt_Cache.Rows[i]["PROCESS_DEPTH"].ToString()) : 0;
                        double INITIAL_HEIGHT = dt_Cache.Rows[i]["INITIAL_HEIGHT"].ToString().Length > 0 ? Convert.ToDouble(dt_Cache.Rows[i]["INITIAL_HEIGHT"].ToString()) : 0;
                        double FACE_HEIGHT = dt_Cache.Rows[i]["FACE_HEIGHT"].ToString().Length > 0 ? Convert.ToDouble(dt_Cache.Rows[i]["FACE_HEIGHT"].ToString()) : 0;
                        string TOOL_NO = dt_Cache.Rows[i]["TOOL_NO"].ToString();
                        double BLADE_LENTH = dt_Cache.Rows[i]["BLADE_LENTH"].ToString().Length > 0 ? Convert.ToDouble(dt_Cache.Rows[i]["BLADE_LENTH"].ToString()) : 0;
                        string sqlwhere = @"PART_NO='" + PartNo + "' and DWG_NO='" + DWGNO + "' and WORK_SURFACE='" + dt_Cache.Rows[i]["WORK_SURFACE"].ToString() + @"'
                           and FEATURE_TYPE='" + dt_Cache.Rows[i]["FEATURE_TYPE"].ToString() + "' and DEEP_CODE='" + dt_Cache.Rows[i]["DEEP_CODE"].ToString() + @"'
                           and COORD_X='" + dt_Cache.Rows[i]["COORD_X"].ToString() + "' ";
                        if (TOOL_NO.Trim().Length <= 0)
                        {
                            string update_sql = @"update [LamexMESManager].[dbo].[NC_PN_AL_TEMP001] set ERR_INFO='无匹配刀具' where " + sqlwhere + " ";
                            BaseBuildSql.ExecuteNonQuery(update_sql);
                            flag_error = true;
                            continue;
                        }
                        if (Math.Round((EXPOSED_LENTH - 5), 2) < Math.Round((FACE_HEIGHT - PROCESS_DEPTH), 2) || Math.Round(BLADE_LENTH, 2) < Math.Round((INITIAL_HEIGHT - PROCESS_DEPTH), 2))
                        {
                            string update_sql = @"update [LamexMESManager].[dbo].[NC_PN_AL_TEMP001] set ERR_INFO='刀具长度不足加工此特征' where " + sqlwhere + " ";
                            BaseBuildSql.ExecuteNonQuery(update_sql);
                            flag_error = true;
                            continue;
                        }

                    }
                    if (flag_error)
                    {
                        DWG_No_Error.Add(DWGNO);
                        Part_No_Error.Add(PartNo);
                        StringBuilder s1 = new StringBuilder();
                        StringBuilder s2 = new StringBuilder();
                        if (!Directory.Exists(@"D:\MESTemp"))
                            Directory.CreateDirectory(@"D:\MESTemp");
                        SaveFileDialog fileDialog = new SaveFileDialog();
                        fileDialog.Title = "导出错误列表";
                        fileDialog.InitialDirectory = @"D:\MESTemp\";//导出默认路径
                        fileDialog.Filter = "Excel文件(*.xlsx)|*.xlsx";//导出默认格式
                        fileDialog.FileName = "MES_TEMP_" + DateTime.Now.ToString("yyMMdd_hhMMss");//导出默认名称
                                                                                                   //DialogResult dialogResult = fileDialog.ShowDialog(this);
                                                                                                   //if (dialogResult == DialogResult.OK)
                                                                                                   //{
                        s1.AppendFormat(@" AND PART_NO IN ('{0}')", string.Join("','", Part_No_Error.ToArray()));
                        s2.AppendFormat(@" AND DWG_NO IN ('{0}')", string.Join("','", DWG_No_Error.ToArray()));
                        string sql = @"SELECT distinct
       [DWG_NO]
      ,[PART_NO]
      ,[WORK_SURFACE]
      ,[FEATURE_TYPE]
      ,[DEEP_CODE]
      ,[COORD_X]
      ,[FEATURE_DIA]
      ,[SLOT_LENGTH]
      ,[SLOT_WIDTH]
      ,[FILLIT_RADIUS]    
      ,[ERR_INFO]
  FROM [LamexMESManager].[dbo].[NC_PN_AL_TEMP001] where 1=1  AND ISNULL(ERR_INFO,'')!=''  " + s1.ToString() + " " + s2.ToString() + "";
                        DataTable dtTemp = BaseBuildSql.GetDataTableBySql(sql);
                        GridControl grid = new GridControl();
                        GridView view = new GridView();
                        grid.ViewCollection.Add(view);
                        grid.MainView = view;
                        view.GridControl = grid;
                        foreach (DataColumn dc in dtTemp.Columns)
                        {
                            DevExpress.XtraGrid.Columns.GridColumn gridColumnNumber = view.Columns.AddVisible(dc.ColumnName);
                            gridColumnNumber.FieldName = dc.ColumnName;
                        }
                        grid.DataSource = dtTemp;
                        this.Controls.Add(grid);
                        grid.ForceInitialize();//强制初始化
                                               //Font font = new Font("宋体", 11, FontStyle.Bold); 
                                               //view.Appearance.HeaderPanel.Font = font;
                                               //view.Appearance.Row.Font = font;            
                        view.BestFitColumns();
                        view.OptionsView.ColumnAutoWidth = false;
                        view.OptionsView.ShowAutoFilterRow = false;
                        view.OptionsPrint.PrintHorzLines = false;//去掉水平网格线
                        view.OptionsPrint.PrintVertLines = false;//去掉垂直网格线
                        view.ExportToXlsx(fileDialog.InitialDirectory + fileDialog.FileName + ".xlsx");
                        //if (DevExpress.XtraEditors.XtraMessageBox.Show("生成错误信息列表成功，是否打开文件？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                        System.Diagnostics.Process.Start(fileDialog.InitialDirectory + fileDialog.FileName + ".xlsx");//打开指定路径下的文件

                    }
                    else
                    {
                        DataView dv = new DataView(dt_Cache);
                        dv.Sort = "DWG_NO,PART_NO,QTY_TYPE,WORK_SURFACE,SUBROUTINE,TOOL_DIA,COORD_X";
                        DataTable dtResult = dv.ToTable(true, new[] { "DWG_NO", "PART_NO", "QTY_TYPE", "WORK_SURFACE", "SUBROUTINE", "TOOL_DIA" });
                        DataTable dt_QTY_TYPE = dv.ToTable(true, new[] { "QTY_TYPE", "QTY" });
                        DataTable dt_SURFACE = dv.ToTable(true, new[] { "WORK_SURFACE" });
                        DataTable dt_SUBROUTINE = dv.ToTable(true, new[] { "SUBROUTINE" });
                        //分别以MLT/MOD作为大分类,再与加工面为小类，分别生成txt
                        for (int i = 0; i < dt_QTY_TYPE.Rows.Count; i++)
                        {
                            string out_put_txt = "";
                            //1、生成MAIN_HEAD文件【MLT】
                            out_put_txt = out_put_txt + Calculate.AL_MAIN.GET_AL_MAIN_HEAD(dt_Cache.Rows[0]["DWG_NO"].ToString(),
                                dt_Cache.Rows[0]["PART_NO"].ToString(),
                                "G54",
                                dt_QTY_TYPE.Rows[i]["QTY"].ToString());

                            for (int j = 0; j < dt_SURFACE.Rows.Count; j++)
                            {
                                //2、生成FACE_HEAD文件 
                                out_put_txt = out_put_txt + Calculate.AL_FACE.GET_AL_FACE_HEAD(
                                dt_Cache.Rows[0]["DWG_NO"].ToString(),
                                dt_Cache.Rows[0]["PART_NO"].ToString(),
                                "G54",
                                dt_QTY_TYPE.Rows[i]["QTY"].ToString(),
                                dt_SURFACE.Rows[j]["WORK_SURFACE"].ToString());
                                DataTable dtFace = dtResult.Select("QTY_TYPE='" + dt_QTY_TYPE.Rows[i]["QTY_TYPE"].ToString() + "' and WORK_SURFACE='" + dt_SURFACE.Rows[j]["WORK_SURFACE"].ToString() + "'").CopyToDataTable();
                                for (int k = 0; k < dtFace.Rows.Count; k++)
                                {
                                    //3、生成子程序                              

                                    if (dtFace.Rows[k]["SUBROUTINE"].ToString().Length < 0)
                                        continue;
                                    string str_SUBROUTINE = dtFace.Rows[k]["SUBROUTINE"].ToString().Substring(2, 4);


                                    //得到每个子程序完整的数据
                                    string DWG_NO = dtFace.Rows[k]["DWG_NO"].ToString();
                                    string PART_NO = dtFace.Rows[k]["PART_NO"].ToString();
                                    string QTY_TYPE = dtFace.Rows[k]["QTY_TYPE"].ToString();
                                    string WORK_SURFACE = dtFace.Rows[k]["WORK_SURFACE"].ToString();
                                    string str_SUBROUTINE1 = dtFace.Rows[k]["SUBROUTINE"].ToString();
                                    string TOOL_DIA = dtFace.Rows[k]["TOOL_DIA"].ToString();
                                    string sqlWhere = @"DWG_NO='" + DWG_NO + "' and PART_NO='" + PART_NO + "' and QTY_TYPE='" + QTY_TYPE + "' and WORK_SURFACE='" + WORK_SURFACE + @"'
                                        and SUBROUTINE='" + str_SUBROUTINE1 + "' and TOOL_DIA='" + TOOL_DIA + "' ";
                                    DataTable dt_TEMP = dt_Cache.Select(sqlWhere).CopyToDataTable();
                                    //临时表升序-【必须定义好排序字段的类型，如dtNew.Columns.Add("COORD_X", typeof(double))】
                                    DataView dvTemp = new DataView(dt_TEMP);
                                    dvTemp.Sort = "DWG_NO,PART_NO,QTY_TYPE,WORK_SURFACE,SUBROUTINE,TOOL_DIA,COORD_X";
                                    dt_TEMP = dvTemp.ToTable();
                                    //【初始高度】【加工深度】
                                    string PROCESS_DEPTH = dt_TEMP.Rows[0]["PROCESS_DEPTH"].ToString();
                                    string INITIAL_HEIGHT = dt_TEMP.Rows[0]["INITIAL_HEIGHT"].ToString();

                                    switch (str_SUBROUTINE)
                                    {
                                        case "HOLE":
                                            out_put_txt = out_put_txt + Calculate.AL_HOLE.GET_AL_HOLE_HEAD(dt_TEMP.Rows[0]["TOOL_NO"].ToString(),
                                                dt_TEMP.Rows[0]["TOOL_DIA"].ToString(),
                                                "G54",
                                                dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString().Length > 0 ? Convert.ToDouble(dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString()).ToString("0.00") : "",
                                                Math.Round(Convert.ToDouble(dt_TEMP.Rows[0]["FACE_HEIGHT"].ToString()) + 60, 1).ToString("0.00"),
                                                Convert.ToDouble(dt_TEMP.Rows[0]["COORD_X"]).ToString("0.00"),//因前面设置了类型，故需要转化
                                                 dt_TEMP.Rows[0]["COORD_Y"].ToString(),
                                                 dt_TEMP.Rows[0]["COMPENSATION_NO"].ToString());
                                            out_put_txt = out_put_txt + Calculate.AL_HOLE.GET_AL_HOLE_CYCLE(dt_TEMP,
                                                INITIAL_HEIGHT.Length > 0 ? Convert.ToDouble(INITIAL_HEIGHT).ToString("0.00") : "",
                                                PROCESS_DEPTH.Length > 0 ? Convert.ToDouble(PROCESS_DEPTH).ToString("0.00") : "");
                                            out_put_txt = out_put_txt + Calculate.AL_HOLE.GET_AL_HOLE_END();
                                            break;
                                        case "TAPP":
                                            out_put_txt = out_put_txt + Calculate.AL_TAPP.GET_TAPP_HEAD(dt_TEMP.Rows[0]["TOOL_NO"].ToString(),
                                                dt_TEMP.Rows[0]["TOOL_DIA"].ToString(),
                                                "G54",
                                                 dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString().Length > 0 ? Convert.ToDouble(dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString()).ToString("0.00") : "",
                                                 Math.Round(Convert.ToDouble(dt_TEMP.Rows[0]["FACE_HEIGHT"].ToString()) + 60, 1).ToString("0.00"),
                                                  Convert.ToDouble(dt_TEMP.Rows[0]["COORD_X"]).ToString("0.00"),//因前面设置了类型，故需要转化
                                                 dt_TEMP.Rows[0]["COORD_Y"].ToString(),
                                                 dt_TEMP.Rows[0]["COMPENSATION_NO"].ToString());
                                            out_put_txt = out_put_txt + Calculate.AL_TAPP.GET_AL_TAPP_CYCLE(dt_TEMP,
                                                INITIAL_HEIGHT.Length > 0 ? Convert.ToDouble(INITIAL_HEIGHT).ToString("0.00") : "",
                                                PROCESS_DEPTH.Length > 0 ? Convert.ToDouble(PROCESS_DEPTH).ToString("0.00") : "");
                                            out_put_txt = out_put_txt + Calculate.AL_TAPP.GET_AL_TAPP_END(dt_TEMP.Rows[0]["FEATURE_TYPE"].ToString());
                                            break;
                                        case "LPCK":
                                            out_put_txt = out_put_txt + Calculate.AL_LPCK.GET_AL_LPCK_HEAD(dt_TEMP.Rows[0]["TOOL_NO"].ToString(),
                                                 dt_TEMP.Rows[0]["TOOL_DIA"].ToString(),
                                                 "G54",
                                                 dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString().Length > 0 ? Convert.ToDouble(dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString()).ToString("0.00") : "");
                                            out_put_txt = out_put_txt + Calculate.AL_LPCK.GET_AL_LPCK_CYCLE(dt_TEMP);

                                            break;
                                        case "RPCK":
                                            out_put_txt = out_put_txt + Calculate.AL_RPCK.GET_AL_RPCK_HEAD(dt_TEMP.Rows[0]["TOOL_NO"].ToString(),
                                                 dt_TEMP.Rows[0]["TOOL_DIA"].ToString(),
                                                 "G54",
                                                 dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString().Length > 0 ? Convert.ToDouble(dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString()).ToString("0.00") : "");
                                            out_put_txt = out_put_txt + Calculate.AL_RPCK.GET_AL_RPCK_CYCLE(dt_TEMP);


                                            break;
                                        case "CPCK":
                                            out_put_txt = out_put_txt + Calculate.AL_CPCK.GET_AL_CPCK_HEAD(dt_TEMP.Rows[0]["TOOL_NO"].ToString(),
                                                 dt_TEMP.Rows[0]["TOOL_DIA"].ToString(),
                                                 "G54",
                                                 dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString().Length > 0 ? Convert.ToDouble(dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString()).ToString("0.00") : "");
                                            out_put_txt = out_put_txt + Calculate.AL_CPCK.GET_AL_CPCK_CYCLE(dt_TEMP);

                                            break;
                                    }
                                }
                                //4、FACE_END文件
                                out_put_txt = out_put_txt + Calculate.AL_FACE.GET_AL_FACE_END(dt_SURFACE.Rows[j]["WORK_SURFACE"].ToString());
                            }
                            //5、生成MAIN_END文件【MLT】
                            out_put_txt = out_put_txt + Calculate.AL_MAIN.GET_AL_MAIN_END();
                            //6、生成txt    
                            string fileName = path + OrderNumber + "_" + PartNo + "_" + dt_QTY_TYPE.Rows[i]["QTY_TYPE"].ToString();
                            FileStream fs = new FileStream(fileName + "_L.NC", FileMode.Create);
                            Common.GetTxtFile.GetTxtNodes(fs, out_put_txt);
                            //7、复制一个R.NC的txt
                            File.Copy(fileName + "_L.NC", fileName + "_R.NC", true);
                            //8、修改R.NC文件机头代码为G55
                            Common.GetTxtFile.EditTxtNodes("G54", "G55", fileName + "_R.NC");

                        }
                        DevExpress.XtraEditors.XtraMessageBox.Show("文件转换成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                      
                    }

                }
                else
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("物料【" + PartNo + "】图纸【" + DWGNO + "】特征数据不存在,请确认!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                SplashScreenTool.CloseSplashScreen();

            }
            catch (Exception ex)
            {
                SplashScreenTool.CloseSplashScreen();
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
            }
        }

        //判断转码程序是否存在
        public bool IsExistNCProgram(string _Code128)
        {
            bool flag = false;
            DirectoryInfo root_Panel = new DirectoryInfo(path_Panel);
            foreach (FileInfo f in root_Panel.GetFiles("*.NC"))
            {
                if (f.Name.Contains(_Code128))
                {
                    flag = true;
                    break;
                }

            }
            return flag;
        }
        // 判断文件是否传送到机器
        public void SendResult(string QRCode)
        {
            // WinAPI 直接调用  2秒后自动关闭 父窗口句柄没有直接用0代替
            MessageBoxTimeoutA((IntPtr)0, "后台程序正在发送......                                        ", "消息框", 0, 0, 3000);
            if (Common.GetDataTable.GetBarCode(QRCode).Rows.Count <= 0)
                MessageBoxTimeoutA((IntPtr)0, "程序已发送，请按启动键！                                        ", "消息框", 0, 0, 3000);
            else
            {
                MessageBoxTimeoutA((IntPtr)0, "程序未发送，正在检查中......                                        ", "消息框", 0, 0, 3000);
                if (Common.GetDataTable.GetBarCode(QRCode).Rows.Count <= 0)
                    MessageBoxTimeoutA((IntPtr)0, "程序已发送，请按启动键！                                        ", "消息框", 0, 0, 3000);
                else
                    //MessageBoxTimeoutA((IntPtr)0, "程序发送失败，请检查服务器！                                        ", "消息框", 0, 0, 3000);
                    XtraMessageBox.Show("程序发送失败，请检查服务器！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        public void ShowInfo(string strOrderNo,string strDwgNo,string strPartNo,int OrderQty)
        {
            int BATCH_QTY = 0, BATCH_COUNT = 0, WAIT_QTY = 0;                
            Calculate.Cal_BatchQtyHelper.Get_BatchQty(strOrderNo, strDwgNo, strPartNo, OrderQty, out BATCH_QTY, out WAIT_QTY, out BATCH_COUNT);
         
            PL_Count = BATCH_COUNT;
            PL_TempCount = Common.GetSerialNumber.GetSerialNo_Custom(strOrderNo + "_" + strPartNo);
            YL_TempCount = Common.GetSerialNumber.GetSerialNo_YL_Custom(strOrderNo + "_" + strPartNo);

            txtBatchQty.Invoke(new Action(() => { txtBatchQty.Text = BATCH_QTY.ToString(); }));
            txtBatchCount.Invoke(new Action(() => { txtBatchCount.Text = BATCH_COUNT.ToString(); }));
            txtWaitQty.Invoke(new Action(() => { txtWaitQty.Text = WAIT_QTY.ToString(); }));
            //显示二维码
            ShowQRCode(OrderQty, BATCH_QTY, WAIT_QTY, strOrderNo + "_" + strPartNo, PL_TempCount);
        }

        //当天产量
        public void GetOutPutInfo()
        {

        //    //累计欠货
        //    txtTotal_NotFinish.Invoke(new Action(() =>
        //{
        //    txtTotal_NotFinish.Text = Calculate.Cal_TotalOutPut.GetNoFinishQty(txtOrderNumber.Text.Trim() + "_" + cbPartNo.Text.Trim()).ToString();
        //}));
        //    //今日完成数量
        //    DataTable dataTable = Common.GetDataTable.Get_TotalToday();
        //    txtOutPutToday.Invoke(new Action(() =>
        //    {
        //        txtOutPutToday.Text = dataTable.Rows[0][0].ToString();
        //    }));
        //    //今日完成工时
        //    txtWorkHourToday.Invoke(new Action(() =>
        //    {
        //        txtWorkHourToday.Text = Calculate.Cal_TotalOutPut.GetTotalWorkHours();
        //    }));

        }
        //加工信息
        public void GetProcessInfo(string _QRCode)
        {
            try
            {
                //加工模式
                string ProcessType = Common.GetScanNCType.GetProcessType_YL(_QRCode);
                //加工数量
                int ProcessQty = 0;

                txtProcessType.Invoke(new Action(() =>
                {
                    txtProcessType.Text = ProcessType;
                }));
                //保存二维码扫码记录
                if (ProcessType.Contains("余量"))
                {
                    ProcessQty = Convert.ToInt32(txtWaitQty.Text.Trim().Length <= 0 ? "0" : txtWaitQty.Text.Trim());
                }
                else
                {
                    ProcessQty = Convert.ToInt32(txtBatchQty.Text.Trim().Length <= 0 ? "0" : txtBatchQty.Text.Trim());
                }
                Common.SQLHelper.Insert_Record(_QRCode, txtMachineNo.Text.Trim(), ProcessQty);
                //计算待加工数量
                txtWaitProcessQty.Invoke(new Action(() =>
                {
                    txtWaitProcessQty.Text = Common.SQLHelper.GetScanQty(txtOrderNumber.Text.Trim() + "_" + cbPartNo.Text.Trim(), Convert.ToInt32(txtOrderQty.Text.Trim())).ToString();
                }));

            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region 一维码扫描
        public void GetOrderInfo(string _Code)
        {
            if (_Code.Length <= 0) return;
            string[] list = _Code.Split('_');
            if (list.Length < 2) return;
            string strORDERNO = list[0];
            string strPARTNO = list[1];
            string strDWGNO = "";
            //int OrderQty = 0;
            txtOrderNumber.Invoke(new Action(() => { txtOrderNumber.Text = strORDERNO; }));
            cbPartNo.Invoke(new Action(() => { cbPartNo.Text = strPARTNO; }));
            Calculate.Cal_BatchQtyHelper.GetDwgNo(strORDERNO, strPARTNO, out strDWGNO);
            cbDwgNo.Invoke(new Action(() => { cbDwgNo.Text = strDWGNO; }));

            //OrderQty = Convert.ToInt32(txtOrderQty.Text.Trim());     
           // ShowInfo(strORDERNO, strDWGNO, strPARTNO, OrderQty);

            //临时放显示图纸号
            ShowPic(strDWGNO, strPARTNO);
        }
      
        #endregion
        #region 二维码
        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <param name="OrderQty">订单数量</param>
        /// <param name="BatchQty">批量数量</param>
        /// <param name="WaitQty">余量数量</param>
        /// <param name="OrderNumber">订单号</param>
        /// <param name="Count">批量累计次数</param>
        public void ShowQRCode(int OrderQty, int BatchQty, int WaitQty, string OrderNumber, int PL_Count)
        {
            if (OrderQty <= 0) return;
            //生成余量二维码
            if (WaitQty == 0)//txtWaitProcessQty.Text.Trim() == "0"|| YL_TempCount > 1
            {
                barCode_ZWS_L.Invoke(new Action(() =>
                {
                    barCode_ZWS_L.Visible = false;
                }));
                barCode_ZWS_R.Invoke(new Action(() =>
                {
                    barCode_ZWS_R.Visible = false;
                }));
            }
            else
            {
                barCode_ZWS_L.Invoke(new Action(() =>
                {
                    barCode_ZWS_L.Visible = true;

                    barCode_ZWS_L.Text = OrderNumber + "_BWS_L_" + YL_TempCount.ToString().PadLeft(3, '0');
                }));
                barCode_ZWS_R.Invoke(new Action(() =>
                {
                    barCode_ZWS_R.Visible = true;
                    barCode_ZWS_R.Text = OrderNumber + "_BWS_R_" + YL_TempCount.ToString().PadLeft(3, '0');
                }));
                // ChangeQRCode("",OrderNumber, YL_TempCount);
            }
            //生成批量二维码
            if (OrderQty < BatchQty)
            {
                barCode_ZPL_L.Invoke(new Action(() =>
                {
                    barCode_ZPL_L.Visible = false;
                }));
                barCode_ZPL_R.Invoke(new Action(() =>
                {
                    barCode_ZPL_R.Visible = false;
                }));
            }
            else
            {
                barCode_ZPL_L.Invoke(new Action(() =>
                {
                    barCode_ZPL_L.Visible = true;
                }));
                barCode_ZPL_R.Invoke(new Action(() =>
                {
                    barCode_ZPL_R.Visible = true;
                }));
                ChangeQRCode("", OrderNumber, PL_Count);
            }
        }

        public void ChangeQRCode(string ORCode, string OrderNumber, int Count)
        {
            //当二维码是余量扫描时，扫描后二维码立即消失
            if (ORCode.Contains("BWS"))
            {
                barCode_ZWS_L.Invoke(new Action(() =>
                {
                    barCode_ZWS_L.Visible = false;
                }));
                barCode_ZWS_R.Invoke(new Action(() =>
                {
                    barCode_ZWS_R.Visible = false;
                }));
            }
            //当二维码是批量扫描时最后一个二维码应消失
            if (Count > PL_Count)
            {
                barCode_ZPL_L.Invoke(new Action(() =>
                {
                    barCode_ZPL_L.Visible = false;
                }));
                barCode_ZPL_R.Invoke(new Action(() =>
                {
                    barCode_ZPL_R.Visible = false;
                }));
                return;
            }


            //颜色变化
            ChangeQRCodeColor(Count);

            //生成批量二维码
            barCode_ZPL_L.Invoke(new Action(() =>
            {
                barCode_ZPL_L.Text = OrderNumber + "_BPL_L_" + Count.ToString().PadLeft(3, '0');
            }));
            barCode_ZPL_R.Invoke(new Action(() =>
            {
                barCode_ZPL_R.Text = OrderNumber + "_BPL_R_" + Count.ToString().PadLeft(3, '0');
            }));

        }
        public void ChangeQRCodeColor(int Count)
        {
            //奇数黑色
            if (Convert.ToBoolean(Count % 2))
            {
                barCode_ZPL_L.Invoke(new Action(() =>
                {
                    barCode_ZPL_L.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(32)))), ((int)(((byte)(31)))), ((int)(((byte)(53)))));
                }));
                barCode_ZPL_R.Invoke(new Action(() =>
                {
                    barCode_ZPL_R.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(32)))), ((int)(((byte)(31)))), ((int)(((byte)(53)))));
                }));
            }
            //偶数红色
            else
            {
                barCode_ZPL_L.Invoke(new Action(() =>
                {
                    barCode_ZPL_L.ForeColor = System.Drawing.Color.Red;
                }));
                barCode_ZPL_R.Invoke(new Action(() =>
                {
                    barCode_ZPL_R.ForeColor = System.Drawing.Color.Red;
                }));
            }
        }
        #endregion
        #region 扫描COM实现
        SerialPort serialPort1 = new SerialPort();
        SerialPort serialPort2 = new SerialPort();
        SerialPort serialPort3 = new SerialPort();
        SerialPort serialPort4 = new SerialPort();
        SerialPort serialPort5 = new SerialPort();
        SerialPort serialPort6 = new SerialPort();
        SerialPort serialPort7 = new SerialPort();
        SerialPort serialPort8 = new SerialPort();
        string COM1 = "";
        string COM2 = "";
        string COM3 = "";
        string COM4 = "";
        string COM5 = "";
        string COM6 = "";
        string COM7 = "";
        string COM8 = "";

        public void InitCom()
        {
            string[] str = SerialPort.GetPortNames();
            if (str == null)
            {
                return;
            }
            Lamex.Common.IniFile ini = new Lamex.Common.IniFile(Application.StartupPath + "\\config\\ComSetting.ini");
            COM1 = ini.IniReadValue("COM Configuration", "COM1");
            COM2 = ini.IniReadValue("COM Configuration", "COM2");
            COM3 = ini.IniReadValue("COM Configuration", "COM3");
            COM4 = ini.IniReadValue("COM Configuration", "COM4");
            COM5 = ini.IniReadValue("COM Configuration", "COM5");
            COM6 = ini.IniReadValue("COM Configuration", "COM6");
            COM7 = ini.IniReadValue("COM Configuration", "COM7");
            COM8 = ini.IniReadValue("COM Configuration", "COM8");
            //添加串口项目
            foreach (string s in System.IO.Ports.SerialPort.GetPortNames())
            {
                //获取有多少个COM口
                if (s == COM1)
                {
                    serialPort1 = new SerialPort();
                    InstanceSerialPort(s, serialPort1);
                }
                else if (s == COM2)
                {
                    serialPort2 = new SerialPort();
                    InstanceSerialPort(s, serialPort2);
                }
                else if (s == COM3)
                {
                    serialPort3 = new SerialPort();
                    InstanceSerialPort(s, serialPort3);
                }
                else if (s == COM4)
                {
                    serialPort4 = new SerialPort();
                    InstanceSerialPort(s, serialPort4);
                }
                else if (s == COM5)
                {
                    serialPort5 = new SerialPort();
                    InstanceSerialPort(s, serialPort5);
                }
                else if (s == COM6)
                {
                    serialPort6 = new SerialPort();
                    InstanceSerialPort(s, serialPort6);
                }
                else if (s == COM7)
                {
                    serialPort7 = new SerialPort();
                    InstanceSerialPort(s, serialPort7);
                }
                else if (s == COM8)
                {
                    serialPort8 = new SerialPort();
                    InstanceSerialPort(s, serialPort8);
                }

            }
            //StartTime();
            //alterTime();
        }

        public void InitSingleCom(string PortName)
        {
            string[] str = SerialPort.GetPortNames();

            //添加串口项目
            foreach (string s in System.IO.Ports.SerialPort.GetPortNames())
            {
                //获取有多少个COM口
                if (s == PortName)
                {
                    serialPort1 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort1);
                }
                else if (s == PortName)
                {
                    serialPort2 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort2);
                }
                else if (s == PortName)
                {
                    serialPort3 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort3);
                }
                else if (s == PortName)
                {
                    serialPort4 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort4);
                }
                else if (s == PortName)
                {
                    serialPort5 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort5);
                }
                else if (s == PortName)
                {
                    serialPort6 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort6);
                }
                else if (s == PortName)
                {
                    serialPort7 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort7);
                }
                else if (s == PortName)
                {
                    serialPort8 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort8);
                }

                System.Threading.Thread.Sleep(1000);

            }
        }
        /// <summary>
        /// 实例化串行端口资源
        /// </summary>
        public void InstanceSerialPort(string comName, SerialPort serialPort)
        {
            try
            {
                //实例化串行端口
                //SerialPort serialPort = new SerialPort();
                //端口名  注:因为使用的是USB转RS232 所以去设备管理器中查看一下虚拟com口的名字
                serialPort.PortName = comName;
                //波特率
                serialPort.BaudRate = 9600;
                //奇偶校验
                serialPort.Parity = Parity.None;
                //停止位
                serialPort.StopBits = StopBits.One;
                //数据位
                serialPort.DataBits = 8;
                //忽略null字节
                serialPort.DiscardNull = true;
                //接收事件
                serialPort.DataReceived += serialPort_DataReceived;
                //开启串口
                serialPort.Open();
                //alterTime();
            }
            catch (Exception ex)
            {
                //XtraMessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort serialPort = (SerialPort)sender;
            try
            {
                ReceiveData(serialPort);
            }
            catch (Exception ex)
            {
                //SetMessage(ex.Message, serialPort.PortName);
            }
        }

        public void ReceiveData(object serialPortobj)
        {
            SerialPort serialPort = (SerialPort)serialPortobj;
            try
            {
                //防止数据接收不完整 线程sleep(100)
                System.Threading.Thread.Sleep(100);

                string strBarcode = serialPort.ReadExisting();
                strBarcode = strBarcode.Replace("\r", "");
                if (strBarcode == string.Empty)
                {
                    return;
                }
                else
                {
                    //一维码扫描
                    if (strBarcode.Length <= 26)
                    {
                        //if (txtOrderQty.Text.Trim().Length <= 0)
                        //{
                        //    DevExpress.XtraEditors.XtraMessageBox.Show("加工数量不能为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        //    txtOrderQty.Focus();
                        //    return;
                        //}
                        //if (IsExistNCProgram(strBarcode))
                        //{
                        ClearControl();
                        //PL_TempCount = Common.GetSerialNumber.GetSerialNo(strBarcode);
                        //YL_TempCount = Common.GetSerialNumber.GetSerialNo_YL(strBarcode);
                        //订单信息
                        GetOrderInfo(strBarcode);
                        GetOutPutInfo();
                        //}
                        //else
                        //{
                        //    DevExpress.XtraEditors.XtraMessageBox.Show("此订单尚未出NC程序，请预转码后再扫描！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        //    return;
                        //}
                    }
                    //二维码扫描
                    else
                    {
                        if (Common.CheckQRCode.CheckIsExistDB(txtMachineNo.Text.Trim()))
                        {
                            DevExpress.XtraEditors.XtraMessageBox.Show("上次扫码记录未传输，请检查服务器！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        if (Common.CheckQRCode.CheckIsOverTime(txtMachineNo.Text.Trim()))
                        {
                            DevExpress.XtraEditors.XtraMessageBox.Show("不能频繁扫码，加工间隔需大于30秒！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        GetProcessInfo(strBarcode);
                        if (strBarcode.Contains("BPL"))
                            PL_TempCount++;

                        //改变二维码内容
                        ChangeQRCode(strBarcode, txtOrderNumber.Text.Trim() + "_" + cbPartNo.Text.Trim(), PL_TempCount);
                        GetOutPutInfo();
                        SendResult(strBarcode);
                    }
                }
            }
            catch (Exception ex)
            {
                //SetMessage(ex.Message, serialPort.PortName);
            }
        }

        private void frmNC_PN_CT_Scan_for_Processing_FormClosed(object sender, FormClosedEventArgs e)
        {
            CloseReceiveData();
        }

        public void Timer_TimesUp(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (COM1 == serialPort1.PortName)
            {
                if (serialPort1.IsOpen != true)
                {
                    serialPort1.Close();
                    InitSingleCom(serialPort1.PortName);
                }
            }
            if (COM2 == serialPort2.PortName)
            {
                if (serialPort2.IsOpen != true)
                {
                    serialPort2.Close();
                    InitSingleCom(serialPort2.PortName);
                }
            }
            if (COM3 == serialPort3.PortName)
            {
                if (serialPort3.IsOpen != true)
                {
                    serialPort3.Close();
                    InitSingleCom(serialPort3.PortName);
                }
            }
            if (COM4 == serialPort4.PortName)
            {
                if (serialPort4.IsOpen != true)
                {
                    serialPort4.Close();
                    InitSingleCom(serialPort4.PortName);
                }

            }
            if (COM5 == serialPort5.PortName)
            {
                if (serialPort5.IsOpen != true)
                {
                    serialPort5.Close();
                    InitSingleCom(serialPort5.PortName);
                }
            }
            if (COM6 == serialPort6.PortName)
            {
                if (serialPort6.IsOpen != true)
                {
                    serialPort6.Close();
                    InitSingleCom(serialPort6.PortName);
                }
            }
            if (COM7 == serialPort7.PortName)
            {
                if (serialPort7.IsOpen != true)
                {
                    serialPort7.Close();
                    InitSingleCom(serialPort7.PortName);
                }
            }
            if (COM8 == serialPort8.PortName)
            {
                if (serialPort8.IsOpen != true)
                {
                    serialPort5.Close();
                    InitSingleCom(serialPort8.PortName);
                }
            }
        }

        public void CloseReceiveData()
        {
            serialPort1.Dispose();
            serialPort2.Dispose();
            serialPort3.Dispose();
            serialPort4.Dispose();
            serialPort5.Dispose();
            serialPort6.Dispose();
            serialPort7.Dispose();
            serialPort8.Dispose();
            serialPort1.Close();
            serialPort2.Close();
            serialPort3.Close();
            serialPort4.Close();
            serialPort5.Close();
            serialPort6.Close();
            serialPort7.Close();
            serialPort8.Close();

        }
        #endregion
    }
}
